﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.BasePages;

namespace Bodenko.Umbraco.Tree.UserControls.umbraco.settings
{
	public partial class editUserControlFile : UmbracoEnsuredPage
	{
		protected override void OnInit(EventArgs e)
		{
			ImageButton button = this.Panel1.Menu.NewImageButton();
			button.Click += new ImageClickEventHandler(this.Save_Click);
			button.AlternateText = "Save User Control File";
			button.ImageUrl = String.Concat(GlobalSettings.Path, "/images/editor/save.gif");
			
			base.Load += new EventHandler(this.Page_Load);
			base.OnInit(e);
		}

		protected void Page_Load(Object sender, EventArgs e)
		{
			String fileName = base.Request.QueryString["file"];
			this.NameTxt.Text = fileName;

			String applicationPath = base.Request.ApplicationPath;
			if (applicationPath == "/")
				applicationPath = "";

			this.lttPath.Text = String.Concat(applicationPath, "/usercontrols/", fileName);
			
			if (!base.IsPostBack && base.Server.MapPath(String.Concat("/usercontrols/", fileName)).StartsWith(base.Server.MapPath("/usercontrols/")))
			{
				using (StreamReader reader = File.OpenText(base.Server.MapPath(String.Concat("/usercontrols/", fileName))))
				{
					String contents = reader.ReadToEnd();

					if (!String.IsNullOrEmpty(contents))
						this.editorSource.Text = contents;
				}
			}

			this.Panel1.Text = "Edit User Control File";
			this.pp_name.Text = "Name";
			this.pp_path.Text = "Path";
		}

		private void Save_Click(Object sender, ImageClickEventArgs e)
		{
			if (this.SaveUserControlFile(this.NameTxt.Text, base.Request.QueryString["file"], this.editorSource.Text))
			{
				base.speechBubble(BasePage.speechBubbleIcon.save, ui.Text("speechBubbles", "fileSavedHeader"), "");
			}
			else
			{
				base.speechBubble(BasePage.speechBubbleIcon.save, ui.Text("speechBubbles", "fileErrorHeader"), ui.Text("speechBubbles", "fileErrorText"));
			}
		}

		public Boolean SaveUserControlFile(String filename, String oldName, String contents)
		{
			try
			{
				if (base.Server.MapPath(String.Concat("/usercontrols/", filename)).StartsWith(base.Server.MapPath("/usercontrols/")))
				{
					using (StreamWriter writer = File.CreateText(base.Server.MapPath(String.Concat("/usercontrols/", filename))))
					{
						writer.Write(contents);
					}

					if ((filename != oldName) && File.Exists(base.Server.MapPath(String.Concat("/usercontrols/", oldName))))
					{
						File.Delete(base.Server.MapPath(String.Concat("/usercontrols/", oldName)));
					}

					return true;
				}

				return false;
			}
			catch
			{
				return false;
			}
		}
	}
}